import { calcFx } from "@/utils/myMath";
import BasicCanvas from "./BasicCanvas";

export class CurveCanvas extends BasicCanvas {
  constructor(
    canvas: HTMLCanvasElement,
    config: CanvasConfig,
    private lst_config: CurveConfigInter[]
  ) {
    super(canvas, config);
    this.init();
  }

  // 初始化
  init() {
    super.init();
    this.ctx.translate(0, this.canvasConfig.height);
    this.ctx.translate(0, this.canvasConfig.startY * this.canvasConfig.scale);

    this.ctx.scale(1, -1);
    this.ctx.translate(
      this.canvasConfig.margin.left,
      this.canvasConfig.margin.bottom
    );
  }

  draw() {
    this.lst_config.map((config) => {
      const { towerPoint } = config;
      const curvePoints = this.calcSingleCurvePoints(config);
      this.drawSingleCurve(towerPoint, curvePoints);
    });
  }

  // 计算单个区段的曲线点坐标
  private calcSingleCurvePoints(config: CurveConfigInter) {
    const { btSpan, Hi, h, w } = config;
    const lst_point = [] as [x: number, y: number][];
    // 计算曲线点的坐标
    for (let m = 0; m < 50; m++) {
      const x = (config.btSpan / 49) * m;
      const fx = calcFx({ H: Hi, w, x, l: btSpan, h });
      const y = (x * h) / btSpan - fx; // 应该计算完成后为负值
      lst_point.push([
        (x / 2) * this.canvasConfig.scale,
        y * 5 * this.canvasConfig.scale,
      ]);
    }
    return lst_point;
  }

  private drawSingleCurve(
    towerPoint: { x0: number; y0: number },
    points: [x: number, y: number][]
  ) {
    // 绘制曲线
    this.ctx.save();
    const { x0, y0 } = towerPoint;
    this.ctx.translate(
      x0 * this.canvasConfig.scale,
      y0 * this.canvasConfig.scale
    );

    super.drawPolyline(points, "#e74c3c", 2);
    this.ctx.restore();
  }
}
